package com.ruoyi.safe.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.safe.constant.CatalogConstants;
import com.ruoyi.safe.domain.BizSafeAttach;
import com.ruoyi.safe.domain.BizSafeDocAttach;
import com.ruoyi.safe.domain.dto.BizCataLogDTO;
import com.ruoyi.safe.domain.dto.BizCatalogDetailRelateAttachDTO;
import com.ruoyi.safe.domain.vo.BizSafeDocAttachVO;
import com.ruoyi.safe.mapper.BizCatalogMapper;
import com.ruoyi.safe.mapper.BizSafeDocAttachMapper;
import com.ruoyi.safe.service.IBizSafeDocAttachService;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.safe.mapper.BizCatalogDetailMapper;
import com.ruoyi.safe.domain.BizCatalogDetail;
import com.ruoyi.safe.service.IBizCatalogDetailService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业内资料目录-详情Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-12-15
 */
@Service
public class BizCatalogDetailServiceImpl implements IBizCatalogDetailService 
{
    @Autowired
    BizCatalogDetailMapper bizCatalogDetailMapper;
    @Autowired
    SysDeptMapper sysDeptMapper;
    @Autowired
    IBizSafeDocAttachService bizSafeDocAttachService;
    @Autowired
    BizSafeDocAttachMapper bizSafeDocAttachMapper;
    /**
     * 查询业内资料目录-详情
     * 
     * @param id 业内资料目录-详情主键
     * @return 业内资料目录-详情
     */
    @Override
    public BizCatalogDetail selectBizCatalogDetailById(Long id)
    {
        BizCatalogDetail bizCatalogDetail = bizCatalogDetailMapper.selectBizCatalogDetailById(id);
        BizSafeDocAttach bizSafeDocAttach = new BizSafeDocAttach();
        bizSafeDocAttach.setCatalogDetailId(id);
        List<BizSafeDocAttachVO> bizSafeDocAttachVOS = bizSafeDocAttachService.selectBizSafeDocAttachList(bizSafeDocAttach);
        bizCatalogDetail.setBizSafeDocAttachList(bizSafeDocAttachVOS);
        return bizCatalogDetail;
    }

    /**
     * 查询业内资料目录-详情列表
     * 
     * @param bizCatalogDetail 业内资料目录-详情
     * @return 业内资料目录-详情
     */
    @Override
    public List<BizCatalogDetail> selectBizCatalogDetailList(BizCatalogDetail bizCatalogDetail)
    {
        List<BizCatalogDetail> list = bizCatalogDetailMapper.selectBizCatalogDetailList(bizCatalogDetail);
        list.stream().forEach(item -> {
            if(StringUtils.isNotNull(item.getDeptId())){
                item.setDeptName(sysDeptMapper.selectDeptById(item.getDeptId()).getDeptName());
            }
        });
        return list;
    }

    /**
     * 新增业内资料目录-详情
     * 
     * @param bizCatalogDetail 业内资料目录-详情
     * @return 结果
     */
    @Override
    public int insertBizCatalogDetail(BizCatalogDetail bizCatalogDetail)
    {
        bizCatalogDetail.setCreateJunior(CatalogConstants.NEED_CREATE_JUNIOR);
        bizCatalogDetail.setParentId(CatalogConstants.ROOT_ID);
        bizCatalogDetail.setAncestors(CatalogConstants.ROOT_ID_CHAR);
        bizCatalogDetail.setUpdateBy(null);
        bizCatalogDetail.setUpdateTime(null);
        bizCatalogDetail.setDeptId(SecurityUtils.getDeptId());
        bizCatalogDetail.setCreateTime(DateUtils.getNowDate());
        bizCatalogDetail.setCreateBy(SecurityUtils.getUsername());
        return bizCatalogDetailMapper.insertBizCatalogDetail(bizCatalogDetail);
    }

    /**
     * 修改业内资料目录-详情
     * 
     * @param bizCatalogDetail 业内资料目录-详情
     * @return 结果
     */
    @Override
    public int updateBizCatalogDetail(BizCatalogDetail bizCatalogDetail)
    {
        if(CatalogConstants.NO_NEED_CREATE_JUNIOR.equals(bizCatalogDetail.getCreateJunior())){
            //如果设置为不需要创建下级，则需要判断这个节点下面是否有下级节点
            List<BizCatalogDetail> juniorBizCatalogDetails =  bizCatalogDetailMapper.selectDetailByParentId(bizCatalogDetail.getId());
            if(juniorBizCatalogDetails.size()>0){
                throw new ServiceException("当前目录存在子级，不能改变'是否创建下级'状态");
            }
        }else if(CatalogConstants.NEED_CREATE_JUNIOR.equals(bizCatalogDetail.getCreateJunior())){
            //设置为需要创建下级，则需要判断目录中没有模板文件
            List<BizSafeDocAttach> bizSafeDocAttaches = bizSafeDocAttachMapper.selectListByDetailId(bizCatalogDetail.getId());
            if(bizSafeDocAttaches.size() > 0){
                //不能设置为需要创建下级
                throw new ServiceException("当前目录存在文件，不能改变'是否创建下级'状态");
            }
        }
        BizCatalogDetail parentBizbizCatalogDetail = bizCatalogDetailMapper.selectBizCatalogDetailById(bizCatalogDetail.getParentId());
        String ancestors = String.valueOf(bizCatalogDetail.getParentId());
        if(parentBizbizCatalogDetail != null){
            ancestors = parentBizbizCatalogDetail.getPath();
        }
        bizCatalogDetail.setAncestors(ancestors);
        bizCatalogDetail.setUpdateBy(SecurityUtils.getUsername());
        bizCatalogDetail.setUpdateTime(DateUtils.getNowDate());
        bizCatalogDetail.setDeptId(SecurityUtils.getDeptId());
        return bizCatalogDetailMapper.updateBizCatalogDetail(bizCatalogDetail);
    }

    /**
     * 批量删除业内资料目录-详情
     * 
     * @param ids 需要删除的业内资料目录-详情主键
     * @return 结果
     */
    @Override
    public int deleteBizCatalogDetailByIds(Long[] ids)
    {
        return bizCatalogDetailMapper.deleteBizCatalogDetailByIds(ids);
    }

    /**
     * 删除业内资料目录-详情信息
     * 
     * @param id 业内资料目录-详情主键
     * @return 结果
     */
    @Override
    public int deleteBizCatalogDetailById(Long id)
    {
        List<BizCatalogDetail> list = bizCatalogDetailMapper.selectDetailByParentId(id);
        //如果该详情下有子数据，先删
        if(list.size() > 0){
            bizCatalogDetailMapper.deleteDetailByParentId(id);
        }
        return bizCatalogDetailMapper.deleteBizCatalogDetailById(id);
    }

    /**
     * 根据目录id查询详情列表
     * @param catalogId
     * @return
     */
    @Override
    public List<BizCatalogDetail> selectListByCatalogId(Long catalogId) {
        List<BizCatalogDetail> list = bizCatalogDetailMapper.selectListByCatalogId(catalogId);
        Long[] deptIds = list.stream().map(item->item.getDeptId()).distinct().collect(Collectors.toList()).toArray(new Long[0]);
        List<SysDept> sysDepts = sysDeptMapper.selectListByIds(deptIds);
        Map<Long,String> sysDeptMap = sysDepts.stream().collect(Collectors.toMap(SysDept::getDeptId,SysDept::getDeptName));
        list.stream().forEach(item -> {
            item.setDeptName(sysDeptMap.get(item.getDeptId()));
        });
        return list;
    }

    /**
     * 新建下级
     * @param bizCatalogDetail
     * @param parentId
     * @return
     */
    @Override
    public int insertLower(Long parentId,BizCatalogDetail bizCatalogDetail) {
        BizCatalogDetail parentBizCatalogDetail = bizCatalogDetailMapper.selectBizCatalogDetailById(parentId);
        //校验是否能够去创建下级
        if(CatalogConstants.NO_NEED_CREATE_JUNIOR.equals(parentBizCatalogDetail.getCreateJunior())){
            //如果父节点不需要要创建下级，则直接返回
            throw new ServiceException(("当前目录不能创建下级"));
        }
        //新建下级的parentId等于上级id
        bizCatalogDetail.setParentId(parentId);
        //目录id
        bizCatalogDetail.setCatalogId(parentBizCatalogDetail.getCatalogId());
        bizCatalogDetail.setCreateBy(SecurityUtils.getUsername());
        bizCatalogDetail.setUpdateTime(DateUtils.getNowDate());
        bizCatalogDetail.setDeptId(SecurityUtils.getDeptId());
        return bizCatalogDetailMapper.insertLower(bizCatalogDetail);
    }

    @Override
    @Transactional
    public int relateAttaches(BizCatalogDetailRelateAttachDTO bizCatalogDetailRelateAttachDTO) {
        List<Long> attachIds = bizCatalogDetailRelateAttachDTO.getAttachIds();
        Long detailId = bizCatalogDetailRelateAttachDTO.getCatalogDetailId();
        //删除目录详情与附件的关联关系
        bizSafeDocAttachMapper.deleteBizSafeDocAttachRelationByDetailId(detailId);
        if(attachIds != null && attachIds.size() > 0){
            //当传入了内业资料文件或者模板文件时，需要检查当前目录是否能否创建下级
            BizCatalogDetail bizCatalogDetail = bizCatalogDetailMapper.selectBizCatalogDetailById(detailId);
            if(CatalogConstants.NEED_CREATE_JUNIOR.equals(bizCatalogDetail.getCreateJunior())){
               //当前目录如果需要创建下级，则不能上传文件
                throw new ServiceException("当前目录需要创建下级，不能上传内业资料文件");
            }else{
                //重新设置关联关系
                return bizSafeDocAttachMapper.setDetailIdByIds(detailId,attachIds.toArray(new Long[0]));
            }
        }
        return 1;
    }
}
